<template>
  <el-container style="height: 100%; border: 1px solid #eee">
    <el-aside width="200px" style="background: #dcdcdc">
      <el-menu :default-openeds="['1']">
        <el-submenu index="1">
          <template slot="title"><i class="el-icon-menu"></i>C2-UFile日志</template>
          <el-menu-item-group>
            <!--<template slot="title">android</template>-->
            <el-menu-item index="2-1" class="new_syslog_class" v-on:click="jumpNewSysLog">去新版日志 ->></el-menu-item>
          </el-menu-item-group>
          <!--<el-menu-item-group-->
            <!--v-for="(sectionItem, sectionIndex) in logCateSectionList" :key="sectionIndex"-->
            <!--:title="sectionItem.sectionTitle">-->
            <!--<el-menu-item-->
              <!--v-for="(childItem, childIndex) in sectionItem.cateList" :key="childIndex"-->
              <!--:index="sectionIndex.toString()+'-'+childIndex.toString()"-->
              <!--v-on:click="selectLeft(childItem.childTitle)">-->
              <!--{{childItem.childTitle}}-->
            <!--</el-menu-item>-->
          <!--</el-menu-item-group>-->
          <el-menu-item-group title="实时日志">
            <el-menu-item index="1-998" v-on:click="run_log('c2_test')">
              测试环境
            </el-menu-item>
          </el-menu-item-group>
        </el-submenu>
      </el-menu>
    </el-aside>

    <el-dialog width="95%" title="解析出的Log信息" :visible.sync="dialogVisible">
      <div class="dialog_content">{{read_file}}</div>
    </el-dialog>

    <el-dialog width="95%" title="实时Log信息" :visible.sync="runLogdialogVisible">
      <el-row style="top: -20px;">
        <el-button type="primary" round v-on:click="wsRefresh">没日志刷新试试</el-button>
        <el-button type="success" round v-on:click="clearRunLog">清空日志</el-button>
        <el-button type="warning" round v-on:click="downloadRunLog">下载日志</el-button>

        <el-button type="info" round>实时日志:{{runLogListCount}} (1000条清空一次)</el-button>
        <!--<el-button style="float: right" type="danger" round>{{inputSearchLog.length > 0? '正在过滤...':'输入即过滤'}}</el-button>-->
        <el-input style="width: 25%;float: right"
                  v-model="inputSearchLog"
                  placeholder="输入即过滤日志"
                  prefix-icon="el-icon-search">
        </el-input>
      </el-row>
      <div class="dialog_content" v-html="runLogShowContent"></div>
      <div ref="divBottom"></div>
    </el-dialog>

    <el-container>
      <div class="input-container">
        <div class="div-input-content">
          <span class="lab-content">
            文件名前缀:
          </span>
          <el-input class="input-content"
                    placeholder="请输入内容"
                    prefix-icon="el-icon-search"
                    v-model="inputFilePrefix">
          </el-input>
        </div>
        <div class="div-input-content-btn">
          <el-button type="primary" icon="el-icon-search" v-on:click="serachClick">搜索</el-button>
          <el-button type="primary" icon="el-icon-delete" v-on:click="clearClick">清空</el-button>
        </div>
      </div>

      <el-header style="text-align: left; font-size: 20px">
        <span>{{logCateName}}-Log</span>
      </el-header>

      <el-main class="main-content">
        <div v-loading="isLoading">
          <el-table
            :data="log_list"
            border
            style="width: 100%"
            :default-sort="{prop: 'CreateTime'}">
            <el-table-column
              fixed
              prop="CreateTime"
              label="CreateTime"
              sortable
              width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.CreateTime | dateFmt}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="BucketName"
              label="BucketName"
              width="120">
            </el-table-column>
            <el-table-column
              prop="FileName"
              label="FileName"
              width="600">
            </el-table-column>
            <el-table-column
              prop="Hash"
              label="Hash"
              width="400">
            </el-table-column>
            <el-table-column
              prop="MimeType"
              label="MimeType"
              width="100">
            </el-table-column>
            <el-table-column
              prop="first_object"
              label="first_object"
              width="200">
            </el-table-column>
            <el-table-column
              prop="Size"
              label="Size"
              width="100">
            </el-table-column>
            <el-table-column
              label="ModifyTime"
              width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.ModifyTime | dateFmt}}</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="100">
              <template slot-scope="scope">
                <el-button @click="handleClick(scope.row, true)" type="text" size="small">查看</el-button>
                <el-button @click="downloadClick(scope.row)" type="text" size="small">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>

      <el-footer>
        <el-button-group class="page-content">
          <el-button type="primary" icon="el-icon-arrow-left" v-on:click="previous">首页</el-button>
          <el-button type="primary" :disabled="!isNext" v-on:click="next">下一页<i
            class="el-icon-arrow-right el-icon--right"></i></el-button>
        </el-button-group>
      </el-footer>

    </el-container>

  </el-container>
</template>

<script>

  import {mapState} from 'vuex'
  import {dateFmt} from '../common/utils/vueDate'
  import {download, downloadHtml} from '../common/utils/download'

  const PAGE_LAST_FILE = "update_page_last_file"

  export default {
    name: 'HelloWorld',
    data() {
      return {
        logCateName: "",
        logCateSectionList: [
          {
            sectionTitle: "machine",
            cateList: [
              {
                childTitle: "machine",
                logPrefix: "gowild_eve_robot_normal"
              },
              {
                childTitle: "machine-unity3d",
                logPrefix: "gowild_eve_robot_u3d"
              }
            ]
          },
          {
            sectionTitle: "android",
            cateList: [
              {
                childTitle: "android-app",
                logPrefix: "gowild_eve_android"
              }
            ]
          },
          {
            sectionTitle: "iOS",
            cateList: [
              {
                childTitle: "iOS-app",
                logPrefix: "gowild_eve_ios"
              }
            ]
          }
        ],
        web_socket: Object,
        serachPrefix: "",
        dialogVisible: false,
        runLogdialogVisible: false,
        download: false,
        inputFilePrefix:'',

        rowData: Object,
        runLogShowContent:'',
        inputSearchLog: '',
        runLogListCount: 0,
        currServer_name: ''
      }
    },
    methods: {
      jumpNewSysLog() {
        window.open("http://logviewer.gowild.top/new_syslog", "_blank");
      },
      run_log(server_name) {
        this.currServer_name = server_name
        this.runLogdialogVisible = true
        //ws://172.27.1.104 发版需修改
        // this.web_socket = new WebSocket('ws://0.0.0.0:5678/echo_ws?service_env='+server_name)
        this.web_socket = new WebSocket('ws://172.27.1.104:5678/echo_ws?service_env='+server_name)
      },
      wsRefresh() {
        this.$store.dispatch('reqReConn')
      },
      clearRunLog() {
        this.runLogShowContent = ''
        this.runLogListCount = 0
        // this.asyncFunData()
      },
      filterRunLog(data) {
        const this_tmp = this
        return new Promise((resolve, reject) => {
          let runLogList_tmp = []
          try {
            if (data == null || data.length <= 0) {
              resolve(runLogList_tmp)
            }
            let pattern = /^(([\[])((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))([ \t\n\x0B\f\r])(([01]?\d|2[0-3]):[0-5]?\d:[0-5]?\d)(\.)(\d+)([\]])).*/gm
            let list_match = data.match(pattern)
            if (list_match != null && list_match.length > 0) {
              list_match.forEach((item) => {
                runLogList_tmp.push(item)
              })
              if (this_tmp.inputSearchLog.length > 0) {
                let runLogList_tmp_search = []
                runLogList_tmp.forEach((item) => {
                  if (item.search(this_tmp.inputSearchLog) != -1) {
                    runLogList_tmp_search.push(item)
                  }
                })
                runLogList_tmp = runLogList_tmp_search
              }
            }
            resolve(runLogList_tmp)
          }catch (e) {
            resolve(runLogList_tmp)
          }
        })
      },
      async asyncFunData(data) {
        try {
          this.filterRunLog(data).then(data => {
            if (data) {
              let runLogShowContent_tmp = ''
              data.forEach((item) => {
                this.runLogListCount++
                runLogShowContent_tmp += `<p style="word-break: break-word;line-height: 2;background-color: burlywood;">${item}</p><hr>`
              })
              this.runLogShowContent += runLogShowContent_tmp
              if (this.runLogListCount > 1000) {
                this.runLogShowContent = ''
                this.runLogListCount = 0
              }
            }
          }).catch(error => {
          })
        } catch (err) {
          console.log('asyncFunData', err)
        }
      },
      downloadRunLog() {
        // download('实时日志_'+new Date().getTime()+'.txt', this.runLogShowContent)
        downloadHtml('实时日志_'+new Date().getTime()+'.html', this.runLogShowContent)
      },
      selectLeft(title) {
        this.logCateName = title
        this.inputFilePrefix = ''
        this.serachClick()
      },
      previous() {
        this.$store.dispatch(PAGE_LAST_FILE, '')
        this.reqFunc()
      },
      next() {
        this.reqFunc()
      },
      handleClick(row, visible) {
        this.download = !visible
        this.rowData = row
        this.$store.dispatch('clear_read_file')
        this.dialogVisible = visible
        let json = {
          parms: {
            read_file: row.FileName
          }
        }
        this.$store.dispatch('reqReadFile', json)
      },
      downloadClick(row) {
        this.handleClick(row, false)
      },
      serachClick() {
        this.serachPrefix = this.inputFilePrefix
        this.$store.dispatch(PAGE_LAST_FILE, '')
        this.reqFunc()
      },
      clearClick() {
        this.inputFilePrefix = ''
      },
      reqFunc() {
        if (this.serachPrefix.length <= 0) {
          if (this.logCateName == this.logCateSectionList[0].cateList[0].childTitle) {
            const log_prefix = this.logCateSectionList[0].cateList[0].logPrefix
            this.serachPrefix = log_prefix
          } else if (this.logCateName == this.logCateSectionList[0].cateList[1].childTitle) {
            const log_prefix = this.logCateSectionList[0].cateList[1].logPrefix
            this.serachPrefix = log_prefix
          } else if (this.logCateName == this.logCateSectionList[1].cateList[0].childTitle) {
            const log_prefix = this.logCateSectionList[1].cateList[0].logPrefix
            this.serachPrefix = log_prefix
          } else if (this.logCateName == this.logCateSectionList[2].cateList[0].childTitle) {
            const log_prefix = this.logCateSectionList[2].cateList[0].logPrefix
            this.serachPrefix = log_prefix
          }
        }
        let json = {
          parms: {
            page_last_file: this.page_last_file,
            page_size: 30,
            prefix: this.serachPrefix
          }
        }
        this.$store.dispatch('reqLogList', json)
      },
    },
    watch: {
      read_file(val) {
        if (val.length > 0 && this.download) {
          download(this.rowData.FileName+'.txt', val)
          this.download = false
        }
      },
      runLogdialogVisible(val) {
        if (!val) {
          this.web_socket.close()
          this.clearRunLog()
        } else {
          this.run_log(this.currServer_name)
        }
      },
      web_socket(val) {
        // let heartbeat_timer = null
        if (val) {
          val.onopen = function(event){
            // heartbeat_timer = setInterval(() => {
            //   this_tmp.keepalive(val)
            // }, 5000)
          }
          val.onmessage = () => {
            if (this.runLogdialogVisible) {
              this.asyncFunData(event.data)
            }
          }
          val.onerror = function(event){
            // clearInterval(heartbeat_timer)
          }
        } else {
          // clearInterval(heartbeat_timer)
        }
      }
    },
    computed: {
      ...mapState(['log_list', 'isLoading', 'page_last_file', 'isNext', 'read_file']),
    },
    filters: {
      dateFmt(time) {
        return dateFmt(time * 1000)
      }
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus" rel="stylesheet/stylus">

  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  .main-content {
    padding 0
  }

  .el-aside {
    color: #333;
  }

  .page-content
    width 100%
    margin-top 10px
    margin-bottom 30px
    margin-left auto
    margin-right auto

  .el-footer
    height 60px
    margin-left auto
    margin-right auto

  .input-container
    padding 15px

  .div-input-content
    float left
    margin-top 15px
    margin-bottom 15px
    width 75%

  .lab-content
    display block
    float left
    width 15%
    line-height 40px

  .input-content
    float left
    width 75% !important

  .div-input-content-btn
    float right
    margin-top 15px
    margin-bottom 15px
    /*margin-right 10%*/

  .dialog_content
    line-height 2
    height 60vh
    word-wrap break-word
    overflow: scroll

  .new_syslog_class
    color red !important

</style>
